package com.xuetang.controller;

import com.xuetang.common.R;
import com.xuetang.entity.BloodSugarRecord;
import com.xuetang.service.BloodSugarRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 血糖记录控制器
 */
@RestController
@RequestMapping("/bloodSugar")
public class BloodSugarRecordController {

    @Autowired
    private BloodSugarRecordService bloodSugarRecordService;

    /**
     * 获取血糖记录列表
     */
    @GetMapping("/records")
    public R<Map<String, Object>> getRecords(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,
            @RequestParam(required = false) Integer type,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {

        // 处理参数
        if (userId == null) {
            return R.error("用户ID不能为空");
        }

        // 如果未指定日期范围，但指定了具体日期
        if (startDate == null && endDate == null && date != null) {
            startDate = date;
            endDate = date;
        }

        // 如果只指定了开始日期，则结束日期默认为今天
        if (startDate != null && endDate == null) {
            endDate = LocalDate.now();
        }

        // 查询记录
        List<BloodSugarRecord> records;
        int total;

        if (startDate != null && endDate != null) {
            // 按日期范围查询
            records = bloodSugarRecordService.getByUserIdAndDateRange(userId, startDate, endDate);
            total = records.size();
        } else {
            // 分页查询所有记录
            records = bloodSugarRecordService.page(userId, type, page, size);
            total = bloodSugarRecordService.count(userId, type);
        }

        // 构建结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", records);
        result.put("total", total);

        return R.success(result);
    }

    /**
     * 获取血糖记录详情
     */
    @GetMapping("/records/{id}")
    public R<BloodSugarRecord> getRecordDetail(@PathVariable Long id) {
        BloodSugarRecord record = bloodSugarRecordService.getById(id);
        if (record == null) {
            return R.error("记录不存在");
        }
        return R.success(record);
    }

    /**
     * 新增血糖记录
     */
    @PostMapping("/records")
    public R<BloodSugarRecord> addRecord(@RequestBody BloodSugarRecord record) {
        // 参数校验
        if (record.getUserId() == null) {
            return R.error("用户ID不能为空");
        }
        if (record.getValue() == null) {
            return R.error("血糖值不能为空");
        }
        if (record.getMeasureType() == null) {
            return R.error("测量类型不能为空");
        }
        if (record.getMeasureTime() == null) {
            // 默认使用当前时间
            record.setMeasureTime(LocalDateTime.now());
        }

        // 保存记录
        record = bloodSugarRecordService.saveRecord(record);
        return R.success(record);
    }

    /**
     * 更新血糖记录
     */
    @PutMapping("/records/{id}")
    public R<BloodSugarRecord> updateRecord(
            @PathVariable Long id,
            @RequestBody BloodSugarRecord record) {

        // 设置ID
        record.setId(id);

        // 更新记录
        record = bloodSugarRecordService.updateRecord(record);
        return R.success(record);
    }

    /**
     * 删除血糖记录
     */
    @DeleteMapping("/records/{id}")
    public R<Boolean> deleteRecord(
            @PathVariable Long id,
            @RequestParam Long userId) {

        // 删除记录
        boolean success = bloodSugarRecordService.deleteById(id, userId);
        if (!success) {
            return R.error("删除失败");
        }
        return R.success(true);
    }

    /**
     * 获取血糖统计数据
     */
    @GetMapping("/statistics")
    public R<Map<String, Object>> getStatistics(
            @RequestParam Long userId,
            @RequestParam(defaultValue = "week") String timeRange) {

        Map<String, Object> statistics = bloodSugarRecordService.getStatistics(userId, timeRange);
        return R.success(statistics);
    }

    /**
     * 获取血糖趋势数据
     */
    @GetMapping("/trend")
    public R<List<Map<String, Object>>> getTrend(
            @RequestParam Long userId,
            @RequestParam(defaultValue = "week") String timeRange) {

        List<Map<String, Object>> trend = bloodSugarRecordService.getTrend(userId, timeRange);
        return R.success(trend);
    }

    /**
     * 获取按测量类型分组的统计数据
     */
    @GetMapping("/by-measure-type")
    public R<List<Map<String, Object>>> getByMeasureType(
            @RequestParam Long userId,
            @RequestParam(defaultValue = "week") String timeRange) {

        List<Map<String, Object>> result = bloodSugarRecordService.getByMeasureType(userId, timeRange);
        return R.success(result);
    }

    /**
     * 判断血糖值状态
     */
    @GetMapping("/check-status")
    public R<Map<String, Object>> checkStatus(
            @RequestParam Double value,
            @RequestParam Integer measureType) {

        int status = bloodSugarRecordService.determineStatus(value, measureType);
        String statusText = "未知";
        String advice = "";

        switch (status) {
            case 1:
                statusText = "正常";
                advice = "您的血糖值在正常范围内，请继续保持良好的生活习惯。";
                break;
            case 2:
                statusText = "偏低";
                advice = "您的血糖值偏低，请适当进食，避免低血糖症状。若感到不适，请及时就医。";
                break;
            case 3:
                statusText = "偏高";
                advice = "您的血糖值偏高，请控制饮食，适量运动。如有不适，请咨询医生。";
                break;
        }

        Map<String, Object> result = new HashMap<>();
        result.put("status", status);
        result.put("statusText", statusText);
        result.put("advice", advice);

        return R.success(result);
    }
}